package com.zs4sdk.activity.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.EventHandler2Get;
import com.common.library.util.ActivityHelper;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.zs4gamesdk.R;
import com.zs4sdk.activity.Zs4GameRetrievePasswordActivityBase;
import com.zs4sdk.common.Extra;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/4/16.
 */

 class Zs4GameOtherAccountLogin extends Zs4GameLoginBase{
    private ViewStub stuPhoneLogin;
    protected Button btnLogin;
    protected TextView tvChangeLogin;
    protected EditText etLoginVerifyCode;
    protected TextView tvInputLoginVerifycodeTipTextView;
    private Button btnGetCode;
    private Button btnForgetPassword;
    private TextView tvPhoneNumber;
    private EditText etInputPwd;
    private  final String sPasswordLogin ;
    private  final String sCodeLogin ;
    private final static int PASSWORD_LOGIN = 1;
    private final static int CODE_LOGIN = 2;
    private int mLoginStyle= PASSWORD_LOGIN;
    protected String mPhoneNumber = "19959720956";
    public static final String LOGINTYPE_EMAIL = "EMAIL";
    public static final String LOGINTYPE_EXCHANGE = "EXCHANGE";
    private View layZ4sgameInputVerifycode;
    private View layZ4sgameLoginInputPassword;
    private MyCount mSendMessageTimer;
    public  final static int LOGIN = 100;
    public  final static int REGIST_AND_LOGIN = 101;
    public  int style = LOGIN;
    public int mCheckPhoneStyle  =  Zs4GameLoginInputPhone.REGIST_SET_PASSOWRD;
    public int mCurrentCheckPhoneStyle = -1;
    public Zs4GameOtherAccountLogin(Activity act, View view, Handler handler) {
        super(act, view,handler);
        sPasswordLogin = mActivity.getString(R.string.zs4_game_password_login);
        sCodeLogin = mActivity.getString(R.string.zs4_game_code_login);
       // mPhoneNumber = phoneNumber;
        stuPhoneLogin = (ViewStub)mMainView.findViewById(R.id.stu_phone_login);
    }
    public Zs4GameOtherAccountLogin(Activity act, View view, Handler handler,int style) {
        this(act, view,handler);
        this.style = style;
    }
    public void setLoginStyle(int style){
        mCheckPhoneStyle = style;
    }
    protected void myInitView(){
        tvPhoneNumber = (TextView)mMainView.findViewById(R.id.tvPhoneNmuber) ;
        layZ4sgameInputVerifycode = mMainView.findViewById(R.id.z4sgame_lin_login_input_verifycode);
        layZ4sgameLoginInputPassword = mMainView.findViewById(R.id.z4sgame_lin_login_input_password);
        tvChangeLogin = (TextView) mMainView.findViewById(R.id.btnChangeLogin);
        btnGetCode = (Button)mMainView.findViewById(R.id.btn_zs4_game_login_get_verify_code);
        btnForgetPassword = (Button)mMainView.findViewById(R.id.btn_zs4_game_forget_password);
        btnLogin = (Button)mMainView.findViewById(R.id.zs4gameviewid_btn_login_with_verifycode);
        etLoginVerifyCode = (EditText)mMainView.findViewById(R.id.zs4_game_edt_input_login_verify_code);
        tvInputLoginVerifycodeTipTextView = (TextView)mMainView.findViewById(R.id.tv_zs4game_txv_input_login_verifycode_tip);
        etInputPwd = (EditText)mMainView.findViewById(R.id.zs4_game_edt_register_input_pwd) ;
        //zs4_game_edt_register_input_pwd
        btnGetCode.setOnClickListener(this);
        tvChangeLogin.setOnClickListener(this);
        btnForgetPassword.setOnClickListener(this);
        if(mOnClickListener != null){
            btnLogin.setOnClickListener(mOnClickListener);
        }
    }
    protected  void initView(){
        if(!mIsInit) {
            myInitView();
            mIsInit = true;
        }
        if(mCheckPhoneStyle == mCurrentCheckPhoneStyle){
            return;
        }
        if(mCheckPhoneStyle == Zs4GameLoginInputPhone.NO_REGIST){
            btnLogin.setText(mActivity.getString(R.string.zs4gamestring_btn_register_and_login));
            TextView tvPhoneText = (TextView)mMainView.findViewById(R.id.tvPhoneText);
            tvPhoneText.setText(mActivity.getString(R.string.zs4game_regist_login));
            tvChangeLogin.setVisibility(View.GONE);
            layZ4sgameLoginInputPassword.setVisibility(View.GONE);
            layZ4sgameInputVerifycode.setVisibility(View.VISIBLE);
        }else if(mCheckPhoneStyle == Zs4GameLoginInputPhone.REGIST_SET_PASSOWRD){
            btnLogin.setText(mActivity.getString(R.string.zs4gamestring_btn_login));
            TextView tvPhoneText = (TextView)mMainView.findViewById(R.id.tvPhoneText);
            tvPhoneText.setText(mActivity.getString(R.string.zs4game_current_phone));
            tvChangeLogin.setVisibility(View.VISIBLE);
            mLoginStyle= PASSWORD_LOGIN;
            layZ4sgameInputVerifycode.setVisibility(View.GONE);
            layZ4sgameLoginInputPassword.setVisibility(View.VISIBLE);
            tvChangeLogin.setText(sCodeLogin);
            etInputPwd.setHint(mActivity.getResources().getString(R.string.zs4Game_input_password));
        }else if(mCheckPhoneStyle == Zs4GameLoginInputPhone.REGIST_NO_PASSWORD){
            btnLogin.setText(mActivity.getString(R.string.zs4gamestring_btn_login));
            TextView tvPhoneText = (TextView)mMainView.findViewById(R.id.tvPhoneText);
            tvPhoneText.setText(mActivity.getString(R.string.zs4game_current_phone));
            tvChangeLogin.setVisibility(View.VISIBLE);
            tvChangeLogin.setText(sPasswordLogin);
            layZ4sgameInputVerifycode.setVisibility(View.VISIBLE);
            layZ4sgameLoginInputPassword.setVisibility(View.GONE);
            mLoginStyle = CODE_LOGIN;
        }
        mCurrentCheckPhoneStyle = mCheckPhoneStyle;
    }

    public void setData(Object data){
        mPhoneNumber = (String)data;
        tvPhoneNumber.setText(mPhoneNumber);

    }
    @Override
    public void login() {
        if(mCheckPhoneStyle == Zs4GameLoginInputPhone.NO_REGIST){
            String verifyCode = etLoginVerifyCode.getText().toString();
            if(verifyCode.length() != 0){
                httpPostLoginByPwd(mPhoneNumber,verifyCode);
            }else{
                ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_code_no_empty));
            }
            return;
        }
        String password = "";
        String verifyCode = "";
        if(mLoginStyle == PASSWORD_LOGIN){
            password = etInputPwd.getText().toString();
            if(password.length() == 0){
                ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_password_no_empty));
                return;
            }
        }else{
            verifyCode = etLoginVerifyCode.getText().toString();
            if(verifyCode.length() == 0){
                ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_code_no_empty));
                return;
            }
        }
        httpPostLoginByPwd(mPhoneNumber,password,verifyCode);
    }
    /**
     * 请求 帐号密码登录(113)
     *
     * @param account
     * @param password
     */
    private void httpPostLoginByPwd(final String account, final String password, String verifycode) {

        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.SHOWPROCESS);
        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        paramList.add(new BasicNameValuePair("account", EncryptHelper.encryptByAES(account)));
        if(password != null && password.length() != 0){
            paramList.add(new BasicNameValuePair("password", EncryptHelper.encryptByAES(EncryptHelper.md5(password))));
        }
        if(verifycode != null && verifycode.length() != 0){
            paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(verifycode)));
        }
        new EventHandler2Get(
                Extra.URL.ACCOUNTLOGINURL,
                paramList,
                ParamsHelper.getUserAgent1(),
                new CommonEventHandler.ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {

                        Log.e("login"," login json result is "+result.toString());
                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS);

                        Message msg = mLoginHandler.obtainMessage();

                        msg.what = Extra.MessageKey.REQUEST_SUCCESS;
                        msg.obj = result;

                        Bundle bundle = new Bundle();
                        bundle.putString("param1", LOGINTYPE_EXCHANGE);
                        bundle.putString("param2", account);
                        bundle.putString("param3", password);

                        msg.setData(bundle);

                        // 发送消息
                        mLoginHandler.sendMessage(msg);
                    }

                    @Override
                    public void doExceptionHandler() {
                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS);
                    }
                });
    }


    @Override
    protected void show() {
        stuPhoneLogin.setVisibility(View.VISIBLE);
    }

    @Override
    protected void hide() {
        stuPhoneLogin.setVisibility(View.GONE);
        if(mSendMessageTimer != null){
            mSendMessageTimer.cancel();
            mSendMessageTimer.onFinish();
        }

    }

    @Override
    public void doOnClick(View v) {
        int id = v.getId();
        if(id == R.id.btnChangeLogin ){
            if(mLoginStyle == CODE_LOGIN){
                tvChangeLogin.setText(sCodeLogin);
                mLoginStyle = PASSWORD_LOGIN;
                layZ4sgameInputVerifycode.setVisibility(View.GONE);
                layZ4sgameLoginInputPassword.setVisibility(View.VISIBLE);
            }else{
                mLoginStyle = CODE_LOGIN;
                tvChangeLogin.setText(sPasswordLogin);
                layZ4sgameInputVerifycode.setVisibility(View.VISIBLE);
                layZ4sgameLoginInputPassword.setVisibility(View.GONE);
            }
        }else if(R.id.btn_zs4_game_login_get_verify_code == id){
            doGetPhoneVerifyCode();
        }else if(R.id.btn_zs4_game_forget_password == id){
           // Zs4GameResetPasswordActivity
            Intent intent = new Intent();
            intent.setClass(mActivity, Zs4GameRetrievePasswordActivityBase.class);
            intent.putExtra("mobile",mPhoneNumber);
            mActivity.startActivity(intent);

        }
    }

    /**
     * function: SDK登录
     *
     * @ author: aXiBa 2013-4-2 下午6:59:12
     */
    private void doExchangeAccount() {
        if (NetworkHelper.isNetworkAvailable(mActivity)) {
            String account = mPhoneNumber;
            String password = etInputPwd.getText().toString().trim();
            if (account.equals("") || password.equals("")) {
                return;
            } else if (password.length() < 6 || password.length() > 12) {
                ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_password_length"));
                return;
            } else {
                httpPostLoginByPwd(account, password,"");
            }
        } else {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }
    /**
     * 获取手机验证码
     */
    private void doGetPhoneVerifyCode() {

        tvInputLoginVerifycodeTipTextView.setText("");
      //  registerInputTipTextView.setText("");
        String sendmode = "1";
        if (isNetworkAvailable()) {
            String phoneNumber = mPhoneNumber;
            mSendMessageTimer = new MyCount(Extra.SDKGAMESTRS.GET_AGAIN, 1000);
            mSendMessageTimer.start();
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumber)));
            new EventHandler2Get(
                    Extra.URL.PHONEVERIFYCODE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new CommonEventHandler.ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {

                    Log.e("phone", "phone result is "+result.toString());

                    Message msg = mLoginHandler.obtainMessage();

                    msg.what = Extra.MessageKey.REQUEST_VERIFY_SUCCESS;
                    msg.obj = result;
                    // 发送消息
                    mLoginHandler.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {
                }
            });
        } else {
            tvInputLoginVerifycodeTipTextView.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network")));
        }
    }

    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {

        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            // 还原btn按钮
            btnGetCode.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_orange_90_bg"));
            btnGetCode.setEnabled(true);
            btnGetCode.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_send_message_verify")));

        //    registerGetVerifyCodeButton.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_orange_90_bg"));
         //   registerGetVerifyCodeButton.setEnabled(true);
         //   registerGetVerifyCodeButton.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_send_message_verify")));

        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnGetCode.setText(millisUntilFinished / 1000 + "s重新发送");
            // 设置btn样式
            btnGetCode.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_gray_90_bg"));
            // 设置不可点击  zs4gamedraw_conner_orange_90_bg
            btnGetCode.setEnabled(false);

          //  registerGetVerifyCodeButton.setText(millisUntilFinished / 1000 + "s重新发送");
            // 设置btn样式
          //  registerGetVerifyCodeButton.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_gray_90_bg"));
            // 设置不可点击
         //   registerGetVerifyCodeButton.setEnabled(false);
        }
    }

    public void setError(String error){
        tvInputLoginVerifycodeTipTextView.setText(error);
    }


    /**
     * 请求 帐号密码登录(113)
     *
     * @param account
     */
    protected void httpPostLoginByPwd(final String account, String verifycode) {

        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.SHOWPROCESS);

        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();

        paramList.add(new BasicNameValuePair("account", EncryptHelper.encryptByAES(account)));
        //  paramList.add(new BasicNameValuePair("password", EncryptHelper.encryptByAES(EncryptHelper.md5(password))));
        paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(verifycode)));
        new EventHandler2Get(
                Extra.URL.REGISTERURL,
                paramList,
                ParamsHelper.getUserAgent1(),
                new CommonEventHandler.ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {

                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS);

                        Message msg = mLoginHandler.obtainMessage();

                        msg.what = Extra.MessageKey.REQUEST_SUCCESS;
                        msg.obj = result;
                        Log.e("reg"," login result is "+result.toString());
                        Bundle bundle = new Bundle();
                        bundle.putString("param1", LOGINTYPE_EXCHANGE);
                        bundle.putString("param2", account);

                        msg.setData(bundle);

                        // 发送消息
                        mLoginHandler.sendMessage(msg);
                    }

                    @Override
                    public void doExceptionHandler() {
                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS);
                    }
                });
    }
}
